package com.guguguweb.conn;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LoginAuthRespHandler extends ChannelInboundHandlerAdapter {

    private Map<String, Boolean> nodeCheck = new ConcurrentHashMap<>();
    private String[] whiteList = {"127.0.0.1", "192.168.1.1"};

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessage message = (NettyMessage) msg;
        if (message.getHeader() != null && message.getHeader().getType() == MessageType.HAND_REQ) {
            String nodeIndex = ctx.channel().remoteAddress().toString();
            NettyMessage loginResp = null;
            //re auth reject
            if (nodeCheck.containsKey(nodeIndex)) {
                loginResp = buildLoginResponse(MessageType.HAND_RESP);
                System.out.println("重复登录");
            } else {
                InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
                String ip = address.getAddress().getHostAddress();
                boolean isOk = false;
                for (String WIP : whiteList) {
                    if (WIP.equals(ip)) {
                        isOk = true;
                        break;
                    }
                }
                System.out.println("验证成功? " + isOk);
                loginResp = isOk ? buildLoginResponse(MessageType.HAND_RESP) : buildLoginResponse(MessageType.NOT_IN_WHITE_LIST);
                if (isOk)
                    nodeCheck.put(nodeIndex, true);
            }
            String body = (String) message.getBody();
            System.out.println("<-----收到握手信息" + body);
            System.out.println("发送握手回应----->" + loginResp);
            ctx.writeAndFlush(loginResp);
        } else {
            //收到其他req
            System.out.println("收到其他req");
            ctx.fireChannelRead(msg);
        }
    }

    private NettyMessage buildLoginResponse(byte result) {
        NettyMessage message = new NettyMessage();
        Header header = new Header();
        header.setType(MessageType.HAND_RESP);
        message.setHeader(header);
        message.setBody(result);
        return message;
    }

    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        nodeCheck.remove(ctx.channel().remoteAddress().toString());
        ctx.close();
        ctx.fireExceptionCaught(cause);
    }
}
